// 登录用户
const express = require('express');
const router = express.Router();
const jwt = require('../jwt');
const { asyncHandle } = require('../getSendResult');
const { login, deleteUser, createUser } = require('../../services/user');
const { deleteUserinfo } = require('../../services/userinfo');

// 创建用户
router.post('/createUser', asyncHandle(
    async (req, res, next) => {
        const username = req.body.username;
        const password = req.body.password;
        return await createUser(username, password);
    }
))


// 用户登录
router.post('/login', asyncHandle(
    async (req, res, next) => {
        const username = req.body.username;
        const password = req.body.password;
        const result = await login(username, password);
        if (result) {
            // 表示登录成功
            // 并把用户id添加到cookie中
            jwt.publish(res, undefined, { id: result.id });
        }
        return result;
    }
))
// 删除用户,同时要删除用户信息
router.get("/deleteUser", asyncHandle(
    async (req, res, next) => {
        await deleteUserinfo(req.id);
        return await deleteUser(req.id);
    }
));


module.exports = router;